package cn.sciento.iam.saas.domain.service.observer;

import java.util.Objects;
import javax.annotation.Nonnull;
import org.apache.commons.lang3.StringUtils;
import cn.sciento.boot.platform.code.builder.CodeRuleBuilder;
import cn.sciento.core.base.BaseConstants;
import cn.sciento.iam.domain.entity.Group;
import cn.sciento.iam.domain.entity.Tenant;
import cn.sciento.iam.domain.repository.GroupRepository;
import cn.sciento.iam.saas.domain.service.TenantObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;

public class TenantGroupObserver implements TenantObserver<Group> {
  private static final Logger LOGGER = LoggerFactory.getLogger(TenantGroupObserver.class);
  
  @Autowired
  private CodeRuleBuilder codeRuleBuilder;
  
  @Autowired
  private GroupRepository groupRepository;
  
  @Override
  public int order() {
    return 20;
  }
  
  @Override
  public Group tenantCreate(@Nonnull Tenant tenant) {
    String groupNum = this.codeRuleBuilder.generateCode("T", BaseConstants.DEFAULT_TENANT_ID, "HPFM.GROUP", "GLOBAL", "GLOBAL", null);
    Group group = new Group();
    group.setGroupNum(groupNum);
    group.setGroupName(tenant.getTenantName());
    group.setTenantId(tenant.getTenantId());
    group.setSourceKey(tenant.getSourceKey());
    group.setSourceCode(StringUtils.defaultIfBlank(tenant.getSourceCode(), "STONG"));
    group.setEnabledFlag(tenant.getEnabledFlag());
    this.groupRepository.insertSelective(group);
    LOGGER.info("[TenantInit - Num={}] -> {}", tenant.getTenantNum(), group);
    return group;
  }
  
  @Override
  public Group tenantUpdate(@Nonnull Tenant tenant) {
    Group group = this.groupRepository.selectByTenantId(tenant.getTenantId());
    Assert.notNull(group, "error.data_not_exists");
    if (!Objects.equals(tenant.getEnabledFlag(), group.getEnabledFlag())) {
      group.setEnabledFlag(tenant.getEnabledFlag());
      this.groupRepository.updateOptional(group, "enabledFlag");
      LOGGER.info("Update tenant group, tenantNum is [{}], group is {}", tenant, group);
    } 
    return group;
  }
}
